package ro.gillardon.commons.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import ro.gillardon.commons.logger.BTPLogger;

/**
 * Static Utility class providing the DIP system configuration.
 *
 * @author lorinczi
 */
public final class ConfigProvider {
  /**
   * Private constructor disable instantiation.
   */

  /**
   * The logger for this class.
   */
  private static final Logger LOG = Logger.getLogger(ConfigProvider.class);
  /**
   * Name of the configuration properties file.
   */
  private static final String CONFIG_FILE = "btp_system_configuration.properties";
  /**
   * The project properties read from the property file.
   */
  private static Properties businessTripPlannerConfig;
  /**
   * Static initialisation. Loads initial configuration.
   */
  static {
    loadConfig();
  }

  /**
   * Private constructor to disable instantiation.
   */
  private ConfigProvider() {
    // Private constructor to disable instantiation.
  }

  /**
   * Loads the businesstripplanner system configuration from a property file.
   */
  public static void loadConfig() {

    Properties config = new Properties();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream fileInStream = loader.getResourceAsStream(CONFIG_FILE);
    if (fileInStream == null) {
      BTPLogger.error(LOG, "config file missing");
      return;
    }
    try {

      config.load(fileInStream);
    } catch (IOException ioe) {
      BTPLogger.error(LOG, "error" + CONFIG_FILE + " || Details: " + ioe);
      return;
    }
    String configFilePath = loader.getResource(CONFIG_FILE).getFile();
    BTPLogger.info(LOG, "config file loaded:" + configFilePath);
    businessTripPlannerConfig = config;

  }

  /**
   * Get the property given by the configParam enum from the properties file.
   *
   * @param configParam
   * @return proprtyValue value
   */

  public static String getProperty(final ConfigParam configParam) {
    String propertyValue = null;
    String propertyKey = configParam.getPropertyKey();
    if (businessTripPlannerConfig == null) {
      BTPLogger.error(LOG, "error");
      return "";
    } else {
      propertyValue = businessTripPlannerConfig.getProperty(propertyKey);
    }
    if (propertyValue == null) {
      BTPLogger.error(LOG, "error");
      return "";
    }
    return propertyValue;
  }

}
